package com.jeeplus.modules.api.utils;

import java.security.MessageDigest;
import java.util.Date;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.jeeplus.common.utils.MD5Util;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.net.HttpClientUtil;

public class CreditCardUtils {
	private static Logger logger = LoggerFactory.getLogger(CreditCardUtils.class);
	private static final String URL = "http://tt.kakacaifu.com";// 测试
	//private static final String URL = "http://channel.idai88.com";// 正式
	private static final String PARTNERID = "2";// 测试商户号
	private static final String KEY = "ahcj123456";// 测试密钥
	//private static final String PARTNERID = "5870";// 商户号
	//private static final String KEY = "9e77361952c6b1c7f17679f50d288359";// 密钥
	public static final String unionLogin = "/flowCloud/third/v2/unionLogin";// 产品进件接口
	public static final String productCode = "/flowCloud/third/v2/productCode";// 产品编码查询接口
	public static final String orderDetail = "/flowCloud/third/v2/orderDetail";// 订单查询
	public static final String stepSearch = "/flowCloud/third/v2/stepSearch";// 进度查询接口
	private static final String hexDigIts[] = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
	
	public static void main(String[] args) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("timestamp", new Date().getTime());
		jsonObject.put("phone", "15981800206");
		jsonObject.put("name", "测试");
		jsonObject.put("idcard", "410100198901011234");
		jsonObject.put("productCode", "789");
		jsonObject.put("productName", "浦发惠军卡");
		
		JSONObject object = send(unionLogin, jsonObject.toString());
		System.out.println(object.toString());
	}
	/**
	 * 发送请求
	 * @param api API接口路径
	 * @param content 业务参数JSON格式
	 * @return
	 */
	public static JSONObject send(String api, String content) {
		JSONObject jsonObject = new JSONObject();
		try {
			Map<String, String> param = Maps.newHashMap();
			param.put("content", content);
			param.put("sign", signV2(content));
			param.put("channelId", PARTNERID);
			System.out.println(param.toString());
			logger.debug("信用卡请求参数：" + param.toString());
			String resultString = HttpClientUtil.doPost(URL + api, param);
			logger.debug("信用卡返回数据：" + resultString);
			jsonObject = JSONObject.parseObject(resultString);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonObject;
	}

	 /**
     * Description:
     * v2 版本联合登录签名
     * @author hsw
     * @param key : 秘钥， map ： 待签名map
     * @CreateDate 2019/7/28 12:02
     */
	private static String signV2(String content) {
        content += "&key=" + KEY;
        return MD5Encode(content, "UTF-8").toUpperCase();
    }

    /**
     * Description:
     * v2版本联合登录签名验证
     * @author hsw
     * @param sign : 签名字符串， map : 待签名map, key : 秘钥
     * @CreateDate 2019/7/28 12:00
     */
    private static boolean verifySignV2(String sign, String content) {
        boolean result = false;
        String verifySignV2 = signV2(content);
        if (sign != null && sign.equals(verifySignV2)) {
            result = true;
        }
        return result;
    }
    
   

    /**
     * MD5加密
     * @param origin 字符
     * @param charsetname 编码
     * @return
     */
    private static String MD5Encode(String origin, String charsetname){
        String resultString = null;
        try{
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if(null == charsetname || "".equals(charsetname)){
                resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
            }else{
                resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
            }
        }catch (Exception e){
        }
        return resultString;
    }


    private static String byteArrayToHexString(byte b[]){
        StringBuffer resultSb = new StringBuffer();
        for(int i = 0; i < b.length; i++){
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }

    private static String byteToHexString(byte b){
        int n = b;
        if(n < 0){
            n += 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigIts[d1] + hexDigIts[d2];
    }
}
